<?php

/*
	Class: PagepartsViewContent

	About: Author
		Rich Joslin

	About: License
		<http://communit.as/docs/license>

	About: See Also
		- <Cts_Db_Table_Abstract>
*/
class PagepartsViewContent extends Cts_Db_Table_Abstract {

	/* Group: Instance Variables */

	/*
		Variable: $_name
	*/
	protected $_name = 'pageparts_vw_content';

	/*
		Variable: $_primary
	*/
	protected $_primary = array('part_id', 'locale', 'version');

	/* Group: Instance Methods */

	/*
		Function: getLatestVersion
			Returns the content row with the highest version number for the specified page part.
	*/
	function getLatestVersion($part_id, $locale) {
		$latest_version = $this->fetchAllArray(
			$this->select()
			->where("part_id = ?", $part_id)
			->where("locale = ?", $locale)
			->order("version desc")
			->limit(1)
		);
		return $latest_version[0];
	}

	/*
		Function: hasVersions
			Returns a boolean describing whether or not a given
			page part has any versions (published or not).
	*/
	function hasVersions($part_id, $locale) {
		$version = $this->fetchRow(
			$this->select()
			->where("part_id = ?", $part_id)
			->where("locale = ?", $locale)
		);
		if (is_null($version)) {
			return false;
		} else {
			return true;
		}
	}

	/*
		Function: hasDraft
			Returns a boolean describing whether or not a given page
			part has a version that is in a draft state (active = 0).
	*/
	function hasDraft($part_id, $locale) {
		$version = $this->fetchRow(
			$this->select()
			->where("part_id = ?", $part_id)
			->where("locale = ?", $locale)
			->where("(active = 0 or publish_on is null or publish_on > '".date(DB_DATETIME_FORMAT)."')")
		);
		if (is_null($version)) {
			return false;
		} else {
			return true;
		}
	}

	/*
		Function: hasArchives
			Returns a boolean describing whether or not a given page part has a
			version that is in an archived state (active = 1 and publish_date <= now).
	*/
	function hasArchives($part_id, $locale) {
		$version = $this->fetchRow(
			$this->select()
			->where("part_id = ?", $part_id)
			->where("locale = ?", $locale)
			->where("active = 1 and publish_on is not null and publish_on <= '".date(DB_DATETIME_FORMAT)."'")
		);
		if (is_null($version)) {
			return false;
		} else {
			return true;
		}
	}

	/*
		Function: getLatestVersion
			Returns a version number that is 0.1 higher than the currently existing highest version.
	*/
	function getNextVersionNumber($part_id, $locale) {
		$latest_version = $this->fetchAllArray(
			$this->select()
			->where("part_id = ?", $part_id)
			->where("locale = ?", $locale)
			->order("version desc")
			->limit(1)
		);
		$latest_version_number = $latest_version[0]['version'];
		$latest_version_number += 0.1;
		return $latest_version_number;
	}

}
